package com.sxt.practiceapplication.utils.okhttp;

import java.io.IOException;
import java.util.Objects;

import okhttp3.Headers;

/**
 * 对OkHttp得到的响应进行封装
 */
public class WrapResponse {

    /**
     * 原Response对象
     */
    private okhttp3.Response realResponse;

    /**
     * 响应体
     */
    private String body;

    /**
     * Http响应状态码
     */
    private int code;

    /**
     * 响应头信息
     */
    private Headers headers;


    private WrapResponse() {
    }

    public synchronized static WrapResponse getInstance(okhttp3.Response response) {
        WrapResponse rs = new WrapResponse();
        rs.realResponse = response;
        try {
            rs.body = Objects.requireNonNull(response.body()).string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        rs.code = response.code();
        rs.headers = response.headers();
        return rs;
    }

    public okhttp3.Response getRealResponse() {
        return realResponse;
    }

    public String getBody() {
        return body;
    }

    public int getCode() {
        return code;
    }

    public Headers getHeaders() {
        return headers;
    }

    /**
     * 获取name对应的响应头信息
     *
     * @param name header名
     * @return 响应头具体信息
     */
    public String getHeader(String name) {
        return this.headers.get(name);
    }
}
